using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;

namespace Pronghorn.Core
{
	public class MinimizeAndCombineCssController : ProngHornControllerBase
	{
		private readonly IFileLocator _fileLocator;
		private readonly IFileMinifier _cssMinifier;

		public MinimizeAndCombineCssController(ViewDataDictionary<IProngHornSkinContext> viewDataDictionary, ISiteContext siteContext, IIocContainer container) : base(viewDataDictionary, siteContext, container)
		{
			_cssMinifier = Container.Resolve<IFileMinifier>();
			_fileLocator = Container.Resolve<IFileLocator>("cssFileLocator");
		}

		private IEnumerable<FilesTagBase> getListOfStyles(IEnumerable<string> fileIds)
		{
			foreach (string fileId in fileIds)
			{
				string[] fileIdParts = fileId.Split('-');
				var fileContext = Container.Resolve<IFileConventions>(fileIdParts[0]);
				string filePath = _fileLocator.GetFileLocation(fileIdParts[1], fileContext);
				yield return new StyleTag(new Uri(filePath, UriKind.RelativeOrAbsolute));
			}
		}

		protected string Render(IEnumerable<FilesTagBase> scripts)
		{
			var writer = new StringWriter();
			foreach (StyleTag styleTag in scripts)
			{
				_cssMinifier.Minify(styleTag.Code, writer);
			}
			return writer.ToString();
		}

		public CssResult Index(string files)
		{
			var result = new CssResult { Content = string.Empty };
			if (files == null)
			{
				files = Request.QueryString["files"];
			}
			if (string.IsNullOrEmpty(files))
			{
				return result;
			}
			result.Content = Render(getListOfStyles(splitArguments(files)));
			return result;
		}

		private static IEnumerable<string> splitArguments(string files)
		{
			if (files.IndexOf(',') > -1)
			{
				return files.Split(',');
			}
			return files.Split('|');
		}
	}
}